/*
 * 创建日期 2009-3-17
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.cpp.web.tag.edit;

import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.jsp.JspException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import  org.fantasy.cpp.web.tag.BaseTag;
import  org.fantasy.common.util.StringUtil;

/**
 * 表单Form
 * 
 * @author: 王文成
 * @version: 1.0
 * @since 2009-3-17
 */
public class FormTag extends BaseTag {
	private static final Log log = LogFactory.getLog(FormTag.class);

	private String name;

	private String action;
	
	private String target;

	public void setName(String name) {
		this.name = name;
	}

	public void setAction(String action) {
		this.action = action;
	}
	public void setTarget(String target) {
		this.target = target;
	}

	@Override
	public int doStartTag() throws JspException {
		StringBuffer html = new StringBuffer(512);
		String formName = StringUtil.isValid(name) ? name : "EditForm";
		String iframe = getResultPageName();
		String ctx = getCtx();
		String url = (ctx + action).replaceFirst("//", "/");
		html.append("<form name=\"" + formName + "\" action=\"" + url + "\" method=\"post\"  target=\"" + iframe + "\" style=\"margin:0px\"/> \n");
		write(html);
		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doEndTag() throws JspException {
		write("</form>\n");
		String resultPage = (String) pageContext.getAttribute("ResultPage");
		write("<iframe name=\"" + resultPage + "\" id=\"" + resultPage + "\" style=\"display:none\"></iframe>");
		return EVAL_PAGE;
	}

	private void write(Object html) {
		Writer out = getJspWriter();
		try {
			out.write(html.toString());
			out.flush();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace(new PrintWriter(out));
		}
	}

	private String getResultPageName() {
		String resultPage = "IFRAME" + System.currentTimeMillis();
		pageContext.setAttribute("ResultPage", resultPage);
		return StringUtil.isValid(target) ? target : resultPage;
	}
}
